<?php

/**
 * Created by PhpStorm.
 * User: feng
 * Date: 2017/1/21
 * Time: 下午7:55
 */
class Lyw_tixian_record_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
    }

//    public function getPayedList(){
//        $sql = "select * from lyw_tixian_record where is_pay = 1;";
//        $list = $this->db->query($sql)->result_array();
//        return $list;
//    }
    public function getPayList($type)
    {
        $sql = "SELECT lyw_tixian_record.* , lyw_user.username FROM lyw_tixian_record INNER JOIN lyw_user ON lyw_tixian_record.user_id=lyw_user.id and lyw_tixian_record.is_pay= ? order by lyw_tixian_record.id desc;";
        $list = $this->db->query($sql, array($type))->result_array();
        return $list;
    }

    public function doPay($id)
    {
        $this->db->trans_start();
        //更新
        $sql = "update lyw_tixian_record set is_pay = 1 , pay_time = ? where id = ?";
        $this->db->query($sql, array(time(), $id));
        $affected_num = $this->db->affected_rows();
        $this->db->trans_complete();
        if ($affected_num == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function getSum()
    {
        $sql = "select sum(money) as sum from lyw_tixian_record where is_pay = 1";
        $row = $this->db->query($sql)->row();
        if (empty($row->sum)) {
            return 0;
        } else {
            return $row->sum;
        }
    }

    public function getListByUserId($user_id)
    {
        $sql = 'select * from lyw_tixian_record where user_id = ? order by id desc limit 0 , 5';
        $list = $this->db->query($sql, array($user_id))->result_array();
        return $list;
    }

    public function insert($user_id, $money, $account)
    {
        $data = array('user_id' => $user_id, 'account' => $account, 'money' => $money, 'creat_time' => time());
        $str = $this->db->insert_string('lyw_tixian_record', $data);
        $this->db->query($str);
        return $this->db->insert_id();
    }

    public function tixian($user_id, $money, $account)
    {
        $this->db->trans_start();
        $this->insert($user_id, $money, $account);
        $this->load->model('Lyw_user_model');
        $this->Lyw_user_model->tixian($user_id);
        $this->db->trans_complete();
    }
}